﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;


namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// TMS关联交易发货明细回写销售订单明细
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TMSShippingOrderReSaleDetailsController : ControllerBase
    {
        private readonly ILogger<TMSShippingOrder_ReSaleDetailsRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;
        public readonly string con_wms_zh;
        public readonly string con_wms_qh;
        public readonly string con_wms_sc;
        public readonly string con_erp;
        public readonly string con_wms_gd;
        public readonly string con_wms_gz;
        public readonly string con_wms_fl;

        public TMSShippingOrderReSaleDetailsController(ILogger<TMSShippingOrder_ReSaleDetailsRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");
            con_wms_zh = _configuration.GetConnectionString("WMSDbConnection_ZH");
            con_wms_qh = _configuration.GetConnectionString("WMSDbConnection");
            con_wms_sc = _configuration.GetConnectionString("WMSDbConnection_YB");
            con_erp = _configuration.GetConnectionString("ERP_DbConnection");
            con_wms_gd = _configuration.GetConnectionString("WMSDbConnection_GD");
            con_wms_gz = _configuration.GetConnectionString("WMSDbConnection_GZ");
            con_wms_fl = _configuration.GetConnectionString("FL_DbConnection");

        }

        /// <summary>
        /// TMS关联交易发货明细回写销售订单明细
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostTMSShippingOrderPriceUpdate([FromBody] TMSShippingOrder_ReSaleDetailsRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            TMSShippingOrder_ReSaleDetailsResponseDto re = new TMSShippingOrder_ReSaleDetailsResponseDto();
            string shippingorderno = strparm.shippingorderno;
            string con_jd = "";
            string eer = "";
            //框架查询方法
            //var data = _WMSTokenCheckService.GetTokenCheckData(supplier_code);
            decimal qty = 0;

            try
            {

                strSql = new StringBuilder();
                strSql.Append(@" select * from shippingorder_main where ccode='" + shippingorderno + "'");
                DataTable dt_ship = DB.Query(strSql.ToString(), con);
                if (dt_ship.Rows.Count>0)
                {
                    string business_type = dt_ship.Rows[0]["business_type"].ToString();
                    string factory_id = dt_ship.Rows[0]["factory_id"].ToString();
                   
                    if (business_type.Contains("wNixk"))
                    {
                        if (factory_id.Trim()=="A01")
                        {
                            con_jd = con_wms_gd;
                        }
                        else if (factory_id.Trim()=="B01")
                        {
                            con_jd = con_wms_qh;
                        }
                        else if (factory_id.Trim()=="E01")
                        {
                            con_jd = con_wms_sc;
                        }
                        else if(factory_id.Trim()=="G01")
                        {
                            con_jd = con_wms_gz;
                        }
                        else if(factory_id.Trim()=="C01")
                        {
                            con_jd = con_wms_zh;
                        }else if (factory_id.Trim() == "GZ01")
                        {
                            con_jd = con_wms_fl;
                        }
                        else
                        {
                            strMsg = "找不到《" + factory_id + "》对应基地编码信息！";
                        }

                        if (strMsg=="")
                        {
                            if (factory_id.Contains("GZ01"))
                            {
                                strSqlList = new List<string>();
                                strSql = new StringBuilder();
                                strSql.Append(@"SELECT ORGANIZATIONID, WAREHOUSEID, CUSTOMERID, CONSIGNEEID, CUSTOMERDESCR1, EDITTIME, SKU, SKUDESCR1, GGXH, SOREFERENCE1, REFLINENO, SOREFERENCE2, SOREFERENCE3, ORDERNO2,LICENSEPLATE, DRIVER, UDF05, UDF06,ADDRESSID, UDF07, UDF08, UDF09, UDF10, TMSORDERNO, ORDERNO, UDF01,SUM(QTY) QTY,BEGINADDRESS  FROM VIEW_GET_TMSSHIPINFO_DATA
 WHERE TMSORDERNO='" + shippingorderno + "' GROUP BY  ORGANIZATIONID, WAREHOUSEID, CUSTOMERID, CONSIGNEEID, CUSTOMERDESCR1, EDITTIME, SKU, SKUDESCR1, GGXH, SOREFERENCE1, REFLINENO, SOREFERENCE2, SOREFERENCE3, ORDERNO2,LICENSEPLATE, DRIVER, UDF05, UDF06, UDF07, UDF08, UDF09, UDF10, TMSORDERNO, ORDERNO, UDF01,ADDRESSID,BEGINADDRESS");
                                DataTable dt_wms_details = DB.OracleQuery(strSql.ToString(), con_wms_fl);
                                if (dt_wms_details.Rows.Count>0)
                                {
                                    strSql = new StringBuilder();
                                    strSql.Append(@"SELECT ORGANIZATIONID, WAREHOUSEID, TMSORDERNO, SUM(QTY) QTY  FROM VIEW_GET_TMSSHIPINFO_DATA
 WHERE TMSORDERNO='" + shippingorderno + "' GROUP BY  ORGANIZATIONID, WAREHOUSEID, TMSORDERNO");
                                    DataTable dt_wms_qtys = DB.OracleQuery(strSql.ToString(), con_wms_fl);
                                    if (dt_wms_qtys.Rows.Count>0)
                                    {
                                        decimal shipment_amounts = DB.ToDecimal(dt_wms_qtys.Rows[0]["QTY"].ToString());
                                        strSql = new StringBuilder();
                                        strSql.Append(@" select * from shippingorder_sales_details where shippingorderno='" + shippingorderno + "' and id not like '%-%' ");
                                        DataTable dt_tms_sales_details = DB.Query(strSql.ToString(), con);
                                        if (dt_tms_sales_details.Rows.Count > 0)
                                        {
                                            string tab_doc_id = dt_tms_sales_details.Rows[0]["tab_doc_id"].ToString();
                                            string status = dt_tms_sales_details.Rows[0]["status"].ToString();
                                            string tenant_id = dt_tms_sales_details.Rows[0]["tenant_id"].ToString();
                                            string form_id = dt_tms_sales_details.Rows[0]["form_id"].ToString();
                                            string process_id = dt_tms_sales_details.Rows[0]["process_id"].ToString();
                                            string owner = dt_tms_sales_details.Rows[0]["owner"].ToString();
                                            string created_by = dt_tms_sales_details.Rows[0]["created_by"].ToString();
                                            string ddate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                                            foreach (DataRow rows in dt_wms_details.Rows)
                                            {
                                                strSql = new StringBuilder();
                                                strSql.Append(@"INSERT INTO  shippingorder_sales_details(id, document_id, tab_doc_id, status, tenant_id, 
form_id, process_id, owner, created_by, creation_date, last_updated_by, last_update_date, object_version_number, sales_order_no, 
customer_code, customer_name, sales_order_line_id, sales_order_line_no, material_code, material_name, material_unit, material_amount, 
shipment_amount, target_address, receipt_man, receipt_tel, receipt_no, target_addressid, shippingorderno, isignin, 
sales_contract_no, sales_order_id, wms_amount,quantity_ratio,outbound_no,delivery_no,start_address) VALUES (uuid(),uuid(), '" + tab_doc_id + "', '" + status + "', '" + tenant_id + "', '" + form_id + "', '" + process_id + "'" +
        ", '" + owner + "', '" + created_by + "', '" + ddate + "', '" + ddate + "', '" + ddate + "', 1, '" + rows["SOREFERENCE1"].ToString() + "', '" + rows["CONSIGNEEID"].ToString() + "', '" + rows["CUSTOMERDESCR1"].ToString() + "'," +
        " " + rows["REFLINENO"].ToString() + ", '" + rows["REFLINENO"].ToString() + "', '" + rows["SKU"].ToString() + "', '" + rows["SKUDESCR1"].ToString() + "', '块', " + rows["QTY"].ToString() + "," +
        " " + rows["QTY"].ToString() + ", '" + rows["UDF06"].ToString() + "', '" + rows["UDF07"].ToString() + "', '" + rows["UDF07"].ToString() + "', '" + shippingorderno + "_" + rows["ADDRESSID"].ToString() + "', '" + rows["ADDRESSID"].ToString() + "', '" + shippingorderno + "'," +
        " '发车完成', '', '" + rows["REFLINENO"].ToString() + "', " + rows["QTY"].ToString() + ", " + Math.Round(DB.ToDecimal(rows["QTY"].ToString()) / shipment_amounts, 2) + ",'" + rows["ORDERNO"].ToString() + "','" + rows["ORDERNO"].ToString() + "','" + rows["BEGINADDRESS"].ToString() + "')");
                                                strSqlList.Add(strSql.ToString());
                                            }

                                            if (strSqlList.Count > 0 && strMsg == "")
                                            {
                                                strSql = new StringBuilder();
                                                strSql.Append("delete from  shippingorder_sales_details where shippingorderno='" + shippingorderno + "' and  id not like '%-%'");
                                                strSqlList.Add(strSql.ToString());

                                                bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                                if (A)
                                                {

                                                }
                                                else
                                                {
                                                    strMsg = "数据库执行失败，请联系管理员";
                                                }
                                            }
                                            else
                                            {
                                                strMsg = "回写记录,请检查清楚再调用";
                                            }
                                        }
                                        else
                                        {
                                            strMsg = "找不到通用关联交易订单行，请联系物流部调整运单销售订单明细行";
                                        }
                                    }




                                                                                             
                                }
                            }
                            else
                            {
                                strSqlList = new List<string>();
                                strSql = new StringBuilder();
                                strSql.Append(@"select tms.shipping_order_no,sum(ship.material_amount) material_amount from 
(select DISTINCT shipping_order_no,sales_order_line_id,shipment_no from tms_logistics_scan_record ) tms left join (select shipment_no,source_no,material_code,material_name,source_item_code,sum(material_amount)material_amount  from shipment_scan_record ship where shipment_no is not null group by shipment_no,material_code,material_name,source_item_code,source_no ) ship on (tms.sales_order_line_id=
ship.source_item_code  and tms.shipment_no=ship.shipment_no) where tms.shipping_order_no='" + shippingorderno + "'  group by tms.shipping_order_no");
                                DataTable dt_ship_amount = DB.Query(strSql.ToString(), con_jd);
                                if (dt_ship_amount.Rows.Count > 0)
                                {
                                    //运单总发货数量
                                    qty = DB.ToDecimal(dt_ship_amount.Rows[0]["material_amount"].ToString());

                                    strSqlList = new List<string>();
                                    strSql = new StringBuilder();
                                    strSql.Append(@"select tms.shipping_order_no,ship.source_no,tms.sales_order_line_id,tms.shipment_no,spc.waybill_no,ship.material_code,ship.material_name,ship.material_amount from 
(select DISTINCT shipping_order_no,sales_order_line_id,shipment_no from tms_logistics_scan_record ) tms inner join (select shipment_no,source_no,material_code,material_name,source_item_code,sum(material_amount)material_amount  from shipment_scan_record ship where shipment_no is not null group by shipment_no,material_code,material_name,source_item_code,source_no ) ship on (tms.sales_order_line_id=
ship.source_item_code  and tms.shipment_no=ship.shipment_no)  left  join  (select distinct shipment_no,waybill_no from shipment_order) spc on tms.shipment_no=spc.shipment_no  where tms.shipping_order_no='" + shippingorderno + "' ");
                                    DataTable dt_sales_details = DB.Query(strSql.ToString(), con_jd);
                                    if (dt_sales_details.Rows.Count > 0)
                                    {
                                        foreach (DataRow item in dt_sales_details.Rows)
                                        {
                                            decimal shipment_amount = DB.ToDecimal(item["material_amount"].ToString());
                                            decimal quantity_ratio = Math.Round(shipment_amount / qty, 2);
                                            string sales_order_line_id = item["sales_order_line_id"].ToString();
                                            string shipment_no = item["shipment_no"].ToString();
                                            string waybill_no = item["waybill_no"].ToString();
                                            strSql = new StringBuilder();
                                            strSql.Append(@"select ORGANIZATION_CODE,HEADER_ID,ORDER_NUMBER,BOOKED_DATE,CUST_PO_NUMBER,CUSTOMER_NUMBER,CUSTOMER_NAME,SALESREP_NAME,ORDER_TYPE,HEADER_CONTACT_NAME CONTACT_NAME,HEADER_PHONE_NUMBER PHONE_NUMBER,SHIP_ADDRESS1,LINE_NUMBER,
LINE_ID,ITEM_NUMBER,ITEM_DESC,UOM,ORDERED_QUANTITY,SHIPPED_QUANTITY,LINE_STATUS,CONCAT('F',SHIP_LOCATION) SHIP_LOCATION  from  apps.CUX_OM_ORDER_DETAIL_V  WHERE 1=1 and LINE_ID='" + sales_order_line_id + "' ");
                                            DataTable dt_erp_sales_details = DB.OracleQuery(strSql.ToString(), con_erp);
                                            if (dt_erp_sales_details.Rows.Count > 0)
                                            {
                                                string erp_sales_order_no = dt_erp_sales_details.Rows[0]["ORDER_NUMBER"].ToString();
                                                string erp_customer_code = dt_erp_sales_details.Rows[0]["CUSTOMER_NUMBER"].ToString();
                                                string erp_customer_name = dt_erp_sales_details.Rows[0]["CUSTOMER_NAME"].ToString();
                                                string erp_sales_order_line_id = dt_erp_sales_details.Rows[0]["LINE_ID"].ToString();
                                                string erp_sales_order_line_no = dt_erp_sales_details.Rows[0]["LINE_NUMBER"].ToString();
                                                string erp_material_code = dt_erp_sales_details.Rows[0]["ITEM_NUMBER"].ToString();
                                                string erp_material_name = dt_erp_sales_details.Rows[0]["ITEM_DESC"].ToString();
                                                string erp_material_unit = dt_erp_sales_details.Rows[0]["UOM"].ToString();
                                                string erp_material_amount = dt_erp_sales_details.Rows[0]["ORDERED_QUANTITY"].ToString();
                                                string erp_target_address = dt_erp_sales_details.Rows[0]["SHIP_ADDRESS1"].ToString();
                                                string erp_receipt_man = dt_erp_sales_details.Rows[0]["CONTACT_NAME"].ToString();
                                                string erp_receipt_tel = dt_erp_sales_details.Rows[0]["PHONE_NUMBER"].ToString();
                                                string erp_receipt_no = shippingorderno + dt_erp_sales_details.Rows[0]["SHIP_LOCATION"].ToString();
                                                string erp_target_addressid = dt_erp_sales_details.Rows[0]["SHIP_LOCATION"].ToString();
                                                string erp_shippingorderno = shippingorderno;
                                                string erp_isignin = "发车完成";
                                                string erp_sales_contract_no = dt_erp_sales_details.Rows[0]["CUST_PO_NUMBER"].ToString();
                                                string erp_sales_order_id = dt_erp_sales_details.Rows[0]["HEADER_ID"].ToString();

                                                strSql = new StringBuilder();
                                                strSql.Append(@" select * from shippingorder_sales_details where shippingorderno='" + shippingorderno + "' and id not like '%-%' ");
                                                DataTable dt_tms_sales_details = DB.Query(strSql.ToString(), con);
                                                if (dt_tms_sales_details.Rows.Count > 0)
                                                {
                                                    string tab_doc_id = dt_tms_sales_details.Rows[0]["tab_doc_id"].ToString();
                                                    string status = dt_tms_sales_details.Rows[0]["status"].ToString();
                                                    string tenant_id = dt_tms_sales_details.Rows[0]["tenant_id"].ToString();
                                                    string form_id = dt_tms_sales_details.Rows[0]["form_id"].ToString();
                                                    string process_id = dt_tms_sales_details.Rows[0]["process_id"].ToString();
                                                    string owner = dt_tms_sales_details.Rows[0]["owner"].ToString();
                                                    string created_by = dt_tms_sales_details.Rows[0]["created_by"].ToString();
                                                    string ddate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                                                    strSql = new StringBuilder();
                                                    strSql.Append(@"INSERT INTO xdap_app_339816648452079617.shippingorder_sales_details(id, document_id, tab_doc_id, status, tenant_id, 
form_id, process_id, owner, created_by, creation_date, last_updated_by, last_update_date, object_version_number, sales_order_no, 
customer_code, customer_name, sales_order_line_id, sales_order_line_no, material_code, material_name, material_unit, material_amount, 
shipment_amount, target_address, receipt_man, receipt_tel, receipt_no, target_addressid, shippingorderno, isignin, 
sales_contract_no, sales_order_id, wms_amount,quantity_ratio,outbound_no,delivery_no) VALUES (uuid(),uuid(), '" + tab_doc_id + "', '" + status + "', '" + tenant_id + "', '" + form_id + "', '" + process_id + "'" +
        ", '" + owner + "', '" + created_by + "', '" + ddate + "', '" + ddate + "', '" + ddate + "', 1, '" + erp_sales_order_no + "', '" + erp_customer_code + "', '" + erp_customer_name + "'," +
        " " + erp_sales_order_line_id + ", '" + erp_sales_order_line_no + "', '" + erp_material_code + "', '" + erp_material_name + "', '" + erp_material_unit + "', " + erp_material_amount + "," +
        " " + shipment_amount + ", '" + erp_target_address + "', '" + erp_receipt_man + "', '" + erp_receipt_tel + "', '" + erp_receipt_no + "', '" + erp_target_addressid + "', '" + erp_shippingorderno + "'," +
        " '" + erp_isignin + "', '" + erp_sales_contract_no + "', '" + erp_sales_order_id + "', " + shipment_amount + ", " + quantity_ratio + ",'" + shipment_no + "','" + waybill_no + "')");
                                                    strSqlList.Add(strSql.ToString());
                                                }
                                                else
                                                {
                                                    strMsg = "找不到通用关联交易订单行，请联系物流部调整运单销售订单明细行";
                                                }
                                            }
                                            else
                                            {
                                                strMsg = "行ID《" + sales_order_line_id + "》ERP找不到相关订单信息，请联系管理员";
                                            }



                                        }

                                        if (strSqlList.Count > 0 && strMsg == "")
                                        {
                                            strSql = new StringBuilder();
                                            strSql.Append("delete from xdap_app_339816648452079617.shippingorder_sales_details where shippingorderno='" + shippingorderno + "' and  id not like '%-%'");
                                            strSqlList.Add(strSql.ToString());

                                            bool A = DB.ExecuteNoQueryTran(strSqlList, con);
                                            if (A)
                                            {

                                            }
                                            else
                                            {
                                                strMsg = "数据库执行失败，请联系管理员";
                                            }
                                        }
                                        else
                                        {
                                            strMsg = "回写记录,请检查清楚再调用";
                                        }
                                    }
                                    else
                                    {
                                        strMsg = "请确认物流运单是否数据丢失或删除,确认失败";
                                    }
                                }
                                else
                                {
                                    strMsg = "WMS获取运单《" + shippingorderno + "》出货数量失败，请检测是否选择错误车牌信息";
                                }
                            }
                        }

                       

                       
                    }
                                 
                }
                else
                {
                    strMsg = "找不到运单=<"+ shippingorderno + ">主表信息！";
                }

            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.status = "成功";
                re.code = "0";
            }
            else
            {
                re.status = "失败";
                re.code = "500";
                re.message = strMsg;
            }


            return new JsonResult(re);
        }

      
    }
}
